<template>
  <div class="container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>添加用户</span>
        </div>
      </template>
      
      <el-form ref="formRef" :model="user" :rules="rules" label-width="120px" style="max-width: 600px;">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="user.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="user.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="管理的宿舍楼ID" prop="dormBuildId">
          <el-input-number v-model="user.dormBuildId" :min="1" />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  data() {
    return {
      user: {
        userName: '',
        password: '',
        dormBuildId: null
      },
      rules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            const response = await axios.post("http://localhost:8080/UserMgr_Web_exploded/users", this.user)
            if (response.data.success) {
              ElMessage.success('添加成功')
              this.$router.push("/users")
            } else {
              ElMessage.error(response.data.message || '添加失败')
            }
          } catch (error) {
            ElMessage.error('添加失败')
            console.error(error)
          }
        }
      })
    },
    resetForm() {
      this.$refs.formRef.resetFields()
    },
    goBack() {
      this.$router.push("/users")
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
}
</style>